package com.leo;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.WritableImage;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

/**
 * @ClassName DraggedCopyDemo
 * @Description
 * @Author wangss
 * @date 2020.06.05 14:12
 * @Version 1.0
 */
public class DraggedCopyDemo extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        AnchorPane an = new AnchorPane();
        an.setStyle("-fx-background-color: #e7eeea");
        Scene scene = new Scene(an);

        HBox hBox = new HBox(30d);

        Label label = new Label("Hello World");

        TextField tf = new TextField();

        hBox.getChildren().addAll(label, tf);

        AnchorPane.setTopAnchor(hBox, 10d);

        an.getChildren().addAll(hBox);
        primaryStage.setScene(scene);
        primaryStage.setTitle("ImageViewDemo");
        primaryStage.setWidth(600d);
        primaryStage.setHeight(600d);
        primaryStage.setResizable(false);
        primaryStage.show();

        // 拖拽检测
        label.setOnDragDetected(event -> {
            Dragboard db = label.startDragAndDrop(TransferMode.MOVE);

            Text text = new Text(label.getText());
            WritableImage writableImage = new WritableImage((int) label.getWidth(), (int) label.getHeight());
            text.snapshot(new SnapshotParameters(), writableImage);
            db.setDragView(writableImage);

            ClipboardContent content = new ClipboardContent();
            content.putString(label.getText());
            db.setContent(content);

        });

        // 事件传递
        tf.setOnDragOver(event -> {
            event.acceptTransferModes(TransferMode.MOVE);
        });

        // 拖拽完成
        tf.setOnDragDropped(event -> {
            tf.setText(event.getDragboard().getString());
            // 事件传递
            event.setDropCompleted(true);
        });

        label.setOnDragDone(event -> {
            if (event.getTransferMode() == TransferMode.MOVE) {
                label.setText("");
            }
        });

    }
}
